import React, { useState, useEffect, useRef } from 'react';
import { Badge, TimePicker, DatePicker } from 'antd'; // 使用DatePicker替代Calendar
import dayjs from 'dayjs';
import style from './index.module.css';


const Ripe = () => {
  // 状态管理
  const [currentDate, setCurrentDate] = useState('');
  const [clientPhone, setClientPhone] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [showSearchResults, setShowSearchResults] = useState(false);
  const [projectSearch, setProjectSearch] = useState('');
  const [selectedProjects, setSelectedProjects] = useState({});
  const [showSpecModal, setShowSpecModal] = useState(false);
  const [currentProjectId, setCurrentProjectId] = useState(null);
  const [selectedSpecId, setSelectedSpecId] = useState('');
  const [selectedDate, setSelectedDate] = useState(null); // 日期选择器使用dayjs对象
  const [selectedTime, setSelectedTime] = useState(null); // 时间选择器使用dayjs对象
  const [projectRemark, setProjectRemark] = useState('');
  const [showDateAppointments, setShowDateAppointments] = useState(false);

  // 引用
  const phoneInputRef = useRef(null);
  const projectListRef = useRef(null);
  const specModalRef = useRef(null);
  const datePickerRef = useRef(null);

  // 模拟客户数据
  const clients = [
    { id: 1, name: "李明", phone: "13800138000", memberId: "VIP001", remark: "常客" },
    { id: 2, name: "张华", phone: "13900139000", memberId: "", remark: "" },
    { id: 3, name: "赵丽", phone: "13700137000", memberId: "VIP005", remark: "颈椎不好" },
    { id: 4, name: "王强", phone: "13600136000", memberId: "", remark: "长期久坐办公室" },
    { id: 5, name: "陈静", phone: "13500135000", memberId: "VIP010", remark: "偏好艾灸" },
    { id: 6, name: "刘强", phone: "13400134000", memberId: "VIP015", remark: "每周五来" },
    { id: 7, name: "孙丽", phone: "13300133000", memberId: "", remark: "新客户" },
    { id: 8, name: "吴敏", phone: "13200132000", memberId: "VIP020", remark: "腿部不适" },
    { id: 9, name: "郑华", phone: "13100131000", memberId: "", remark: "" },
    { id: 10, name: "钱明", phone: "13000130000", memberId: "VIP025", remark: "全身按摩" }
  ];

  // 项目及规格数据
  const projectSpecifications = {
    tuina: {
      name: "推拿按摩",
      specs: [
        { id: "tuina-30", duration: "30分钟", price: "¥98" },
        { id: "tuina-60", duration: "60分钟", price: "¥168" },
        { id: "tuina-90", duration: "90分钟", price: "¥238" }
      ]
    },
    zhenjiu: {
      name: "针灸治疗",
      specs: [
        { id: "zhenjiu-30", duration: "30分钟", price: "¥128" },
        { id: "zhenjiu-60", duration: "60分钟", price: "¥198" }
      ]
    },
    aijiu: {
      name: "艾灸调理",
      specs: [
        { id: "aijiu-30", duration: "30分钟", price: "¥88" },
        { id: "aijiu-60", duration: "60分钟", price: "¥158" },
        { id: "aijiu-90", duration: "90分钟", price: "¥218" }
      ]
    },
    baguan: {
      name: "拔罐疗法",
      specs: [
        { id: "baguan-20", duration: "20分钟", price: "¥68" },
        { id: "baguan-45", duration: "45分钟", price: "¥98" }
      ]
    },
    foot: {
      name: "中药泡脚+足底按摩",
      specs: [
        { id: "foot-60", duration: "60分钟", price: "¥98" },
        { id: "foot-80", duration: "80分钟", price: "¥128" }
      ]
    },
    scraping: {
      name: "刮痧疗法",
      specs: [
        { id: "scraping-20", duration: "20分钟", price: "¥58" },
        { id: "scraping-30", duration: "30分钟", price: "¥88" }
      ]
    },
    shoulder: {
      name: "肩颈理疗",
      specs: [
        { id: "shoulder-30", duration: "30分钟", price: "¥88" },
        { id: "shoulder-45", duration: "45分钟", price: "¥128" },
        { id: "shoulder-60", duration: "60分钟", price: "¥168" }
      ]
    }
  };

  // 初始化日期和时间
  useEffect(() => {
    const now = dayjs();

    // 设置当前日期显示
    setCurrentDate(now.format('YYYY年MM月DD日 dddd'));

    // 初始化日期和时间选择器
    setSelectedDate(now);
    setSelectedTime(now);

    // 点击外部关闭搜索结果和弹窗
    const handleClickOutside = (event) => {
      if (phoneInputRef.current && !phoneInputRef.current.contains(event.target)) {
        setShowSearchResults(false);
      }

      if (specModalRef.current && !specModalRef.current.contains(event.target)) {
        setShowSpecModal(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 处理日期选择变化
  const handleDateChange = (date) => {
    setSelectedDate(date);
    // 显示该日期的已有预约
    if (date) {
      setShowDateAppointments(true);
      // 3秒后自动隐藏预约信息
      setTimeout(() => setShowDateAppointments(false), 3000);
    }
  };

  // 搜索客户
  const handlePhoneSearch = (value) => {
    setClientPhone(value);
    if (value.length >= 1) {
      const filtered = clients.filter(client =>
        client.phone.includes(value) ||
        client.name.toLowerCase().includes(value.toLowerCase())
      );
      setSearchResults(filtered);
      setShowSearchResults(true);
    } else {
      setShowSearchResults(false);
    }
  };

  // 选择客户
  const selectClient = (phone) => {
    setClientPhone(phone);
    setShowSearchResults(false);
  };

  // 过滤项目
  const filteredProjects = Object.entries(projectSpecifications).filter(([, project]) => {
    if (!projectSearch) return true;
    return project.name.toLowerCase().includes(projectSearch.toLowerCase());
  });

  // 处理项目选择
  const handleProjectChange = (projectId, checked) => {
    if (checked && !selectedProjects[projectId]) {
      setCurrentProjectId(projectId);
      setSelectedSpecId(projectSpecifications[projectId].specs[0].id);
      setShowSpecModal(true);
    } else if (!checked) {
      const updated = { ...selectedProjects };
      delete updated[projectId];
      setSelectedProjects(updated);
    }
  };

  // 确认规格选择
  const confirmSpecification = () => {
    if (currentProjectId && selectedSpecId) {
      const project = projectSpecifications[currentProjectId];
      const spec = project.specs.find(s => s.id === selectedSpecId);

      if (spec) {
        setSelectedProjects(prev => ({
          ...prev,
          [currentProjectId]: {
            specId: selectedSpecId,
            duration: spec.duration,
            price: spec.price
          }
        }));
      }
    }
    setShowSpecModal(false);
    setCurrentProjectId(null);
  };

  // 移除已选项目
  const removeProject = (projectId, e) => {
    if (e) e.stopPropagation();

    const updated = { ...selectedProjects };
    delete updated[projectId];
    setSelectedProjects(updated);

    const checkbox = document.querySelector(`input[name="project"][value="${projectId}"]`);
    if (checkbox) {
      checkbox.checked = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    setClientPhone('');
    setProjectSearch('');
    setSelectedProjects({});
    setProjectRemark('');

    // 重置日期和时间为当前时间
    const now = dayjs();
    setSelectedDate(now);
    setSelectedTime(now);

    document.querySelectorAll('input[name="project"]').forEach(checkbox => {
      checkbox.checked = false;
    });
  };

  // 保存记录
  const saveRecord = () => {
    // 验证
    if (!clientPhone) {
      alert('请输入联系电话');
      return;
    }

    if (Object.keys(selectedProjects).length === 0) {
      alert('请至少选择一个项目');
      return;
    }

    if (!selectedDate || !selectedTime) {
      alert('请选择预约日期和时间');
      return;
    }

    // 构建记录数据
    const selectedProjectDetails = Object.entries(selectedProjects).map(([projectId, spec]) => {
      const project = projectSpecifications[projectId];
      return `${project.name}(${spec.duration} ${spec.price})`;
    }).join('、');

    // 格式化预约时间
    const appointmentDateTime = new Date(
      selectedDate.year(),
      selectedDate.month(),
      selectedDate.date(),
      selectedTime.hour(),
      selectedTime.minute()
    );

    console.log({
      phone: clientPhone,
      projects: selectedProjectDetails,
      appointmentTime: appointmentDateTime,
      remark: projectRemark
    });

    alert('记录保存成功！');
    resetForm();
  };

  return (
    <div className={style.container}>
      {/* 主内容区 */}
      <main className={style.mainContent}>
        {/* 记录表单 */}
        <div className={style.formContainer}>
          {/* 联系电话输入框 */}
          <div className={style.card}>
            <h3 className={style.sectionTitle}>
              <i className={`fa fa-phone ${style.icon}`}></i> 联系电话
            </h3>

            <div className={style.phoneSearchContainer} ref={phoneInputRef}>
              <input
                type="tel"
                value={clientPhone}
                onChange={(e) => handlePhoneSearch(e.target.value)}
                className={style.phoneInput}
                placeholder="输入电话号码搜索客户"
                autoComplete="off"
              />
              <i className={`fa fa-search ${style.searchIcon}`}></i>

              {showSearchResults && (
                <div className={style.searchResults}>
                  {searchResults.length > 0 ? (
                    searchResults.map(client => (
                      <div
                        key={client.id}
                        className={style.searchResultItem}
                        onClick={() => selectClient(client.phone)}
                      >
                        <div className={style.clientName}>
                          {client.name.charAt(0)}{["丽", "静", "敏"].includes(client.name.charAt(1)) ? "女士" : "先生"}
                        </div>
                        <div className={style.clientPhone}>{client.phone}</div>
                        {client.remark && (
                          <div className={style.clientRemark}>{client.remark}</div>
                        )}
                      </div>
                    ))
                  ) : (
                    <div className={style.noResults}>没有找到匹配的客户</div>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* 项目信息区域 */}
          <div className={style.card}>
            <h3 className={style.sectionTitle}>
              <i className={`fa fa-list-alt ${style.icon}`}></i> 项目信息
            </h3>

            {/* 项目搜索框 */}
            <div className={style.projectSearchContainer}>
              <input
                type="text"
                value={projectSearch}
                onChange={(e) => setProjectSearch(e.target.value)}
                className={style.projectSearchInput}
                placeholder="搜索项目..."
              />
              <i className={`fa fa-search ${style.searchIcon}`}></i>
            </div>

            <div className={style.projectContent}>
              {/* 项目选择列表 */}
              <div>
                <label className={style.label}>选择项目（可多选） <span className={style.required}>*</span></label>
                <div className={style.projectList} ref={projectListRef}>
                  {filteredProjects.length > 0 ? (
                    filteredProjects.map(([id, project]) => (
                      <label
                        key={id}
                        className={`${style.checkboxItem} ${selectedProjects[id] ? style.selected : ''}`}
                        data-id={id}
                        onClick={() => {
                          const isSelected = !!selectedProjects[id];
                          handleProjectChange(id, !isSelected);
                        }}
                      >
                        <input
                          type="checkbox"
                          name="project"
                          value={id}
                          checked={!!selectedProjects[id]}
                          onChange={(e) => {
                            e.stopPropagation();
                            handleProjectChange(id, e.target.checked);
                          }}
                          className={style.checkbox}
                        />
                        <span className={style.projectName}>{project.name}</span>
                        {selectedProjects[id] && (
                          <span className={style.selectedSpec}>
                            ({selectedProjects[id].duration} {selectedProjects[id].price})
                          </span>
                        )}
                      </label>
                    ))
                  ) : (
                    <div className={style.noResults}>
                      没有找到匹配的项目，请尝试其他关键词
                    </div>
                  )}
                </div>
              </div>

              {/* 已选项目标签区域 */}
              <div className={style.selectedProjectsSection}>
                <label className={style.label}>已选项目</label>
                <div className={style.tagsContainer}>
                  {Object.keys(selectedProjects).length > 0 ? (
                    <div className={style.tagsList}>
                      {Object.entries(selectedProjects).map(([projectId, spec]) => {
                        const project = projectSpecifications[projectId];
                        return (
                          <div
                            key={projectId}
                            className={style.selectedTag}
                            onClick={(e) => removeProject(projectId, e)}
                          >
                            {project.name}({spec.duration} {spec.price})
                            <span
                              className={style.tagClose}
                              onClick={(e) => removeProject(projectId, e)}
                            >
                              <i className="fa fa-times-circle"></i>
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <div className={style.emptyTagsHint}>请从上方选择项目</div>
                  )}
                </div>
              </div>

              {/* 预约日期选择 - 使用弹出式DatePicker */}
              <div className={style.formGroup} ref={datePickerRef}>
                <label className={style.label}>预约日期</label>
                <DatePicker
                  value={selectedDate}
                  onChange={handleDateChange}
                  format="YYYY年MM月DD日"
                  placeholder="选择预约日期"
                  className={style.datePickerInput}
                  placement="bottomLeft" // 强制向下
                />
              </div>

              {/* 预约时间选择 */}
              <div className={style.formGroup}>
                <label className={style.label}>预约时间</label>
                <TimePicker
                  value={selectedTime}
                  onChange={setSelectedTime}
                  format="HH:mm"
                  minuteStep={15}
                  className={style.timePicker}
                  placeholder="选择预约时间"
                />
              </div>

              {/* 项目备注 */}
              <div className={style.formGroup}>
                <label className={style.label}>项目备注</label>
                <textarea
                  value={projectRemark}
                  onChange={(e) => setProjectRemark(e.target.value)}
                  className={style.textarea}
                  placeholder="例如：客户要求重点按摩肩颈"
                ></textarea>
              </div>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className={style.buttonGroup}>
            <button
              className={style.btnSecondary}
              onClick={resetForm}
            >
              <i className="fa fa-refresh mr-1"></i> 重置
            </button>
            <button
              className={style.btnPrimary}
              onClick={saveRecord}
            >
              <i className="fa fa-save mr-1"></i> 保存记录
            </button>
          </div>
        </div>
      </main>

      {/* 项目规格选择弹窗 */}
      {showSpecModal && currentProjectId && (
        <div
          className={`${style.modalBackdrop} ${showSpecModal ? style.active : ''}`}
          ref={specModalRef}
        >
          <div className={style.modalContent}>
            <div className={style.modalHeader}>
              <h3 className={style.modalTitle}>
                选择 {projectSpecifications[currentProjectId].name} 规格
              </h3>
              <button
                className={style.closeModalBtn}
                onClick={() => setShowSpecModal(false)}
              >
                <i className="fa fa-times"></i>
              </button>
            </div>

            <div className={style.specOptions}>
              {projectSpecifications[currentProjectId].specs.map(spec => (
                <label
                  key={spec.id}
                  className={style.specOption}
                  onClick={() => setSelectedSpecId(spec.id)}
                >
                  <input
                    type="radio"
                    name="specification"
                    value={spec.id}
                    checked={selectedSpecId === spec.id}
                    onChange={(e) => {
                      e.stopPropagation();
                      setSelectedSpecId(e.target.value);
                    }}
                    className={style.radio}
                  />
                  <span className={style.specText}>{spec.duration}</span>
                  <span className={style.specPrice}>{spec.price}</span>
                </label>
              ))}
            </div>

            <div className={style.modalFooter}>
              <button
                className={style.btnSecondary}
                onClick={() => setShowSpecModal(false)}
              >
                取消
              </button>
              <button
                className={style.btnPrimary}
                onClick={confirmSpecification}
              >
                确认选择
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Ripe;